<template>
  <div class="image-upload">
    <el-upload
      class="image-uploader"
      :action="upload.url"
      :headers="upload.headers"
      :show-file-list="false"
      :on-success="handleSuccess"
      :before-upload="beforeUpload"
      :on-error="handleError"
      :on-progress="handleProgress"
    >
      <img v-if="imageUrl" :src="imageUrl" class="image">
      <el-icon v-else class="image-uploader-icon"><Plus /></el-icon>
      <div v-if="progress" class="progress">
        <el-progress :percentage="progress" :show-text="false"></el-progress>
      </div>
    </el-upload>
    <div v-if="imageUrl" class="image-actions">
      <el-button link @click="handlePreview">预览</el-button>
      <el-button link @click="handleOcrImage">OCR识别</el-button>
      <el-button link @click="handleRemove">删除</el-button>
    </div>
    <el-dialog v-model="previewVisible" append-to-body>
      <img width="100%" :src="imageUrl" alt="Preview Image">
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, watch } from 'vue'
import { getToken } from "@/utils/auth"
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'

const props = defineProps({
  modelValue: {
    type: String,
    default: ""
  },
  limit: {
    type: Number,
    default: 1
  }
})

const emit = defineEmits(['update:modelValue', 'on-success', 'on-error', 'on-remove', 'on-ocr', 'ocrData'])

const upload = ref({
  url: import.meta.env.VITE_APP_BASE_API + "/common/upload",
  headers: { Authorization: "Bearer " + getToken() }
})

const imageUrl = ref(props.modelValue)
const progress = ref(0)
const previewVisible = ref(false)

watch(() => props.modelValue, (val) => {
  imageUrl.value = val
}, { immediate: true })

const handleSuccess = (res) => {
  progress.value = 0
  console.log('Upload response:', res)
  if (res.code === 200) {
    let url = ''
    if (res.data && res.data.url) {
      url = res.data.url
    } else if (res.data && typeof res.data === 'string') {
      url = res.data
    } else if (res.fileName) {
      url = res.fileName
    }
    
    if (url) {
      if (!url.startsWith('http')) {
        url = import.meta.env.VITE_APP_BASE_API + url
      }
      console.log('Final image URL:', url)
      imageUrl.value = url
      emit('update:modelValue', url)
      emit('on-success', { url })
    } else {
      ElMessage.error("上传成功但返回数据格式不正确")
      console.error('Invalid response format:', res)
    }
  } else {
    ElMessage.error(res.msg || "上传失败")
    console.error('Upload failed:', res)
  }
}

const handleError = (error) => {
  progress.value = 0
  console.error('Upload error:', error)
  ElMessage.error("上传失败")
  emit('on-error')
}

const handleProgress = (event) => {
  progress.value = Math.round(event.percent)
}

const beforeUpload = (file) => {
  const isImage = file.type.startsWith("image/")
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error("上传文件只能是图片格式!")
    return false
  }
  if (!isLt2M) {
    ElMessage.error("上传图片大小不能超过 2MB!")
    return false
  }
  console.log('File to upload:', file)
  return true
}

const handlePreview = () => {
  previewVisible.value = true
}

const handleOcrImage = () => {
  if (!imageUrl.value) {
    ElMessage.error('请先上传图片')
    return
  }
  
  // 获取图片并转换为 base64
  fetch(imageUrl.value, { cache: 'no-store' })
    .then(response => {
      if (!response.ok) {
        throw new Error(`Failed to fetch image: ${response.status} ${response.statusText}`)
      }
      return response.blob()
    })
    .then(blob => {
      return new Promise((resolve, reject) => {
        const reader = new FileReader()
        reader.onload = () => {
          try {
            // 保留完整的 base64 数据（包括前缀）
            const base64 = reader.result
            console.log('提取的完整图片 base64 数据长度:', base64.length)
            console.log('图片MIME类型:', blob.type)
            
            // 确保图片数据格式正确
            const isJpgOrPng = blob.type === 'image/jpeg' || blob.type === 'image/png' || blob.type === 'image/bmp'
            if (!isJpgOrPng) {
              ElMessage.warning('图片格式不是 JPG/PNG/BMP，OCR 可能无法正常工作')
            }
            
            resolve(base64)
          } catch (error) {
            reject(error)
          }
        }
        reader.onerror = (error) => reject(error)
        reader.readAsDataURL(blob)
      })
    })
    .then(base64 => {
      console.log('提取图片 base64 成功，准备发送 OCR 请求')
      // 发出带有完整 base64 数据（包括前缀）的事件
      emit('ocrData', base64)
    })
    .catch(error => {
      console.error('获取图片失败', error)
      ElMessage.error('获取图片失败: ' + error.message)
    })
}

const handleRemove = () => {
  imageUrl.value = ""
  emit('update:modelValue', "")
  emit('on-remove')
}
</script>

<style lang="scss" scoped>
.image-upload {
  .image-uploader {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    width: 178px;
    height: 178px;
    display: flex;
    justify-content: center;
    align-items: center;

    &:hover {
      border-color: #409EFF;
    }

    .image-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      line-height: 178px;
      text-align: center;
    }

    .image {
      width: 178px;
      height: 178px;
      display: block;
    }

    .progress {
      position: absolute;
      bottom: 0;
      left: 0;
      right: 0;
      background: rgba(255, 255, 255, 0.8);
      padding: 5px;
    }
  }

  .image-actions {
    margin-top: 10px;
    text-align: center;
  }
}
</style>